package com.hong.spring.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author: csh
 * @Date: 2021/1/19 11:45
 * @Description:WebSocket服务器使用独立的线程启动
 */
@Log4j2
public class WebsocketServer {
    @Autowired
    private ServerBootstrap serverBootstrap;

    private ChannelFuture serverChannelFuture;

    @Autowired
    private EventLoopGroup bossGroup;

    @Autowired
    private EventLoopGroup workerGroup;

    private ChannelHandler websocketChannelInitializer;


    private int port;

    public ChannelHandler getWebsocketChannelInitializer() {
        return websocketChannelInitializer;
    }

    public void setWebsocketChannelInitializer(ChannelHandler websocketChannelInitializer) {
        this.websocketChannelInitializer = websocketChannelInitializer;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     *
     * 功能描述: websocket服务器
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2021/1/19 11:45
     */
    public void start() {
        try {
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(websocketChannelInitializer);
            serverChannelFuture = serverBootstrap.bind(port).sync();

            log.info("WEBSOCKET服务启动完成，已绑定端口： " + port);
        } catch (Exception e) {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            log.error("WEBSOCKET服务启动异常！", e);
        }
    }
    /**
     *
     * 功能描述: 关闭Netty Websocket服务器，主要是释放连接
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2021/1/19 11:48
     */
    public void close() {
        serverChannelFuture.channel().close();
        Future<?> bossGroupFuture = bossGroup.shutdownGracefully();
        Future<?> workerGroupFuture = workerGroup.shutdownGracefully();

        try {
            bossGroupFuture.await();
            workerGroupFuture.await();
            log.info("websocket服务停止中...");
        } catch (InterruptedException ignore) {
            ignore.printStackTrace();
        }
    }
}
